package com.xesj.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.xesj.util.Json;
import com.xesj.model.User;
import com.xesj.service.UserServiceI;
import com.xesj.util.PageData;

@Controller
public class LoginController extends BaseController{
	@Autowired
	private UserServiceI userService;
	
	/**
	 *去登录页面	 
	 */
	@RequestMapping("/toLoginPage")
	public String tologinPage (){
		
		return "main/login";
		
	}
	
	//登陆提交地址，和shiro配置文件中配置的loginurl一致
		@RequestMapping(value="login")
		public String login(HttpServletRequest request)throws Exception{
			Json json = new Json();
			// 错误信息
			String errInfo = "";
			// 0：验证成功
			int isSucCode = 0;
			//如果登陆失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
			String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
			//根据shiro返回的异常类路径判断，抛出指定异常信息
			if(exceptionClassName!=null){
				if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
					//最终会抛给异常处理器
					isSucCode = 1;
					errInfo = "账号不存在或已作废";
					/*throw new CustomException("账号不存在");*/
				} else if (AuthenticationException.class.getName().equals(exceptionClassName)){
					//最终会抛给异常处理器
					isSucCode = 1;
					errInfo = "账号不存在或已作废";
				}else if (IncorrectCredentialsException.class.getName().equals(
						exceptionClassName)) { 
					isSucCode = 2;
					errInfo = "密码错误";
					/*throw new CustomException("密码错误");*/
				} else if("randomCodeError".equals(exceptionClassName)){
					isSucCode = 3;
					errInfo = "验证码错误";
					/*throw new CustomException("验证码错误");*/
				}else {
					isSucCode = 4;
					errInfo = "未知错误，请联系管理员";
					/*throw new CustomException("未知错误，请联系管理员");*/
				}
			}
			json.setMsg(errInfo);
			json.setObj(isSucCode);
			request.setAttribute("errMsg", errInfo);
			//此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径
			//登陆失败还到login页面
			return "main/login";
		}
		
	
	
	/**进入系统
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/toIndex")
	public String toMain()throws Exception{	
		return "main/index";
	}
	
	
	/**显示首页
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/showMain")
	public String showIndex()throws Exception{
		return "main/main";
	}
	
	
}
